import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { useFormik } from 'formik';
import styles from './index.module.scss';

import * as Yup from 'yup';
import { useDispatch } from 'react-redux';
import { loginAction, sendCodeAction } from '@/store/action/login';
import { useEffect, useRef, useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { Toast } from 'antd-mobile';
import { LocationStateType } from '@/components/AuthRoute';

export default function Login() {
  const [second, setSecond] = useState(0);
  const timerIdRef = useRef(-1);

  const history = useHistory();
  const { state } = useLocation<LocationStateType>();

  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      mobile: '13566667777',
      code: '',
    },
    onSubmit: async (values) => {
      await dispatch(loginAction(values.mobile, values.code));
      history.replace(state?.fromPath || '/');

      Toast.show({ content: '登录成功', icon: 'success' });
    },

    validationSchema: Yup.object().shape({
      mobile: Yup.string()
        .required('手机号码不能为空')
        .matches(/^1[3-9]\d{9}$/, '请输入正确的手机号码'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '请输入6为验证码'),
    }),
  });

  const handleSendCode = () => {
    dispatch(sendCodeAction(formik.values.mobile));
    setSecond(60);
    timerIdRef.current = window.setInterval(() => {
      setSecond((preSecond) => {
        if (preSecond === 1) {
          clearInterval(timerIdRef.current);
        }
        return preSecond - 1;
      });
    }, 100);
  };

  useEffect(() => {
    return () => {
      clearInterval(timerIdRef.current);
    };
  }, []);

  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          <Input
            autoFocus
            className="input"
            placeholder="请输入手机号"
            autoComplete="off"
            type="text"
            name="mobile"
            maxLength={11}
            value={formik.values.mobile}
            onChange={formik.handleChange}
            errorMsg={formik.touched.mobile ? formik.errors.mobile : ''}
            onBlur={formik.handleBlur}
          />

          <Input
            className="xxx"
            placeholder="请输入验证码"
            autoComplete="off"
            type="text"
            name="code"
            maxLength={6}
            value={formik.values.code}
            onChange={formik.handleChange}
            errorMsg={formik.touched.code ? formik.errors.code : ''}
            extra={
              second === 0 ? <span onClick={handleSendCode}>发送验证码</span> : `${second}秒后获取`
            }
            onBlur={formik.handleBlur}
          />

          <button type="submit" className="login-btn" disabled={!formik.isValid}>
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
